/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-11 17:52:20
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-03-12 17:49:08
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import {
  Alert,
  AutoComplete,
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  List,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Tag,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';
import SimpleTable from 'components/SimpleTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './enterprise.less';

const FormItem = Form.Item;

const { Option } = Select;

@connect(
  ({
    companyStorePage,
    dict,
    contractList,
    enterpriseList,
    employeeList,
    familyList,
    loading,
  }) => ({
    companyStorePage,
    enterpriseList,
    dict,
    contractList,
    employeeList,
    familyList,
    loading: loading.models.companyStorePage,
  })
)
@Form.create()
export default class TableList extends PureComponent {
  state = {
    dataSource: [], // 企业名称 数据源
    result: [], // 企业名称 自动匹配结果
    companyId: '', // 企业id
    contractId: '', // 合同id
    contarctValue: '',
    type: 'add',
  };

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;

    // 查询员工详情
    if (query) {
      const { companyId } = query;
      dispatch({
        type: 'employeeList/employeeDetail',
        payload: {
          id: query.id,
        },
      });
      dispatch({
        type: 'enterpriseList/positionList',
        payload: {
          companyId,
        },
      });
      dispatch({
        type: 'contractList/getList',
        payload: { companyId },
      });
      this.setState({
        type: 'edit',
      });
    }

    // 查询公司
    dispatch({
      type: 'companyStorePage/companyList',
      payload: {
        name: '',
      },
      callback: res => {
        const newList = res.data.map(v => {
          return <Option value={v.id}>{v.name}</Option>;
        });
        this.setState({
          dataSource: newList,
          result: newList,
        });
      },
    });

    // 查询门店
    dispatch({
      type: 'dict/dictStoreList',
      payload: {
        cityId: '',
        institutionId: '',
        name: '',
        provinceId: '',
      },
    });

    // 查询省份
    dispatch({
      type: 'dict/dictProvinceList',
      payload: {},
    });
  }

  onSelect = v => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'contractList/getList',
      payload: { companyId: v },
    });

    this.setState(
      {
        companyId: v,
        contarctValue: '',
      },
      () => {
        dispatch({
          type: 'enterpriseList/positionList',
          payload: {
            companyId: v,
          },
        });
      }
    );

    form.setFieldsValue({ companyId: v });
  };

  onChangeH = (v, t) => {
    if (!t) {
      return;
    }
    const {
      props: { children },
    } = t;
    this.setState({
      contractId: v,
      contarctValue: children,
    });
  };

  // 查询门店
  handleSearchForm = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'dict/dictStoreList',
        payload: { ...fieldsValue },
      });
    });
  };

  // 查询公司
  handleSearch = value => {
    const { dataSource } = this.state;
    const newList = dataSource.filter(v => v.props.children.indexOf(value) > -1);
    this.setState({ result: newList });
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      employeeList: { familyList },
      location: { query },
    } = this.props;
    const { type } = this.state;
    form.validateFields((err, fieldsValue) => {
      // if (err) return;

      const params = {
        ...fieldsValue,
        familyList,
      };
      if (query) {
        params.id = query.id;
      }
      dispatch({
        type: type === 'add' ? 'employeeList/employeeAdd' : 'employeeList/employeeEdit',
        payload: params,
        callback: res => {
          if (res.success) {
            let secondsToGo = 3;
            const modal = Modal.success({
              title: type === 'add' ? '新增成功' : '修改成功',
              content: `将在${secondsToGo}秒后返回员工列表页面`,
              okText: '知道了',
            });
            const timer = setInterval(() => {
              secondsToGo -= 1;
              modal.update({
                content: `将在${secondsToGo}秒后返回员工列表页面`,
              });
            }, 1000);
            setTimeout(() => {
              clearInterval(timer);
              modal.destroy();
              dispatch(routerRedux.push('/Enterprise/employee-list'));
            }, secondsToGo * 1000);
            //message.success();
          } else {
            message.info(res.errorDesc);
          }
        },
      });
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'employeeList/addFamilyList',
    });
  };

  handleInputChange = (e, r, n) => {
    let value = '';
    if (typeof e === 'string') {
      value = e;
    } else {
      value = e.target.value;
    }
    const { dispatch } = this.props;

    const { key } = r;
    const newobj = { ...r };
    newobj[n] = value;
    //console.log(newobj);
    dispatch({
      type: 'employeeList/editFamilyList',
      payload: newobj,
    });
  };

  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/Enterprise/employee-list'));
  };

  renderOptionsC = () => {
    const {
      dict: { cityList },
    } = this.props;
    const options = cityList.map(v => <Option value={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsP = () => {
    const {
      dict: { provinceList },
    } = this.props;
    const options = provinceList.map(v => <Option value={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsPosition = () => {
    const {
      enterpriseList: { positionList },
    } = this.props;
    const options = positionList.map(v => <Option value={v.id}>{v.name}</Option>);
    return options;
  };

  renderOptionsH = () => {
    const {
      contractList: { list },
    } = this.props;
    const options = list.map(v => <Option value={v.id}>{v.title}</Option>);
    return options;
  };

  deleteFamily = r => {
    const {
      dispatch,
      location: { query },
    } = this.props;
    const { type } = this.state;
    if (type != 'add') {
      dispatch({
        type: 'familyList/familyDelete',
        payload: { id: r.id },
        callback: () => {
          const { companyId } = query;
          dispatch({
            type: 'employeeList/employeeDetail',
            payload: {
              id: query.id,
            },
          });
        },
      });
    } else {
      dispatch({
        type: 'employeeList/deleteFamilyList',
        payload: { ...r },
      });
    }
  };

  render() {
    const {
      loading,
      form,
      employeeList: { familyList, detailData },
    } = this.props;

    const { result, contarctValue, type } = this.state;
    const { getFieldDecorator } = form;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Input defaultValue={v} onChange={e => this.handleInputChange(e, r, 'name')} />
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '性别',
        dataIndex: 'sex',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Select
              placeholder="请选择"
              style={{ width: 350 }}
              defaultValue={v}
              onChange={e => this.handleInputChange(e, r, 'sex')}
            >
              <Option key={1}>男</Option>
              <Option key={2}>女</Option>
            </Select>
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '家属关系',
        dataIndex: 'relationType',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Select
              placeholder="请选择"
              style={{ width: 350 }}
              defaultValue={v}
              onChange={e => this.handleInputChange(e, r, 'relationType')}
            >
              <Option key={1}>父母</Option>
              <Option key={2}>子女</Option>
              <Option key={3}>夫妻</Option>
              <Option key={4}>其他</Option>
            </Select>
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '婚姻状况',
        dataIndex: 'marriageStatus',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Select
              placeholder="请选择"
              style={{ width: 350 }}
              defaultValue={v}
              onChange={e => this.handleInputChange(e, r, 'marriageStatus')}
            >
              <Option key={1}>未婚</Option>
              <Option key={2}>已婚</Option>
            </Select>
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '证件号',
        dataIndex: 'identityNo',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Input defaultValue={v} onChange={e => this.handleInputChange(e, r, 'identityNo')} />
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
        render: (v, r) =>
          r.type === 'add' || r.type === 'edit' ? (
            <Input defaultValue={v} onChange={e => this.handleInputChange(e, r, 'mobile')} />
          ) : (
            <span>{v}</span>
          ),
      },
      {
        title: '操作',
        render: (v, r) => <a onClick={() => this.deleteFamily(r)}>删除</a>,
      },
    ];

    const detailInfo = type === 'add' ? {} : detailData;

    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <Alert message="员工信息" type="info" />
          <Form layout="inline">
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="企业名称">
                  {getFieldDecorator('companyId', {
                    initialValue: detailInfo?.companyId,
                    rules: [{ required: true, message: '请输入企业名称' }],
                  })(
                    <Select
                      showSearch
                      placeholder="输入企业名称查询"
                      style={{ width: 350 }}
                      optionFilterProp="children"
                      onChange={this.onSelect}
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {result}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="合同名称">
                  {getFieldDecorator('contractId', {
                    initialValue: detailInfo?.contractId,
                    rules: [{ required: true, message: '请选择合同名称' }],
                  })(
                    <Select
                      placeholder="请选择"
                      style={{ width: 350 }}
                      onChange={this.onChangeH}
                      autoClearSearchValue
                      allowClear
                      value={contarctValue}
                    >
                      {this.renderOptionsH()}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="姓名&#12288;&#12288;">
                  {getFieldDecorator('name', {
                    initialValue: detailInfo?.name,
                    rules: [{ required: true, message: '请输入' }],
                  })(<Input style={{ width: 350 }} />)}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="性别&#12288;&#12288;">
                  {getFieldDecorator('sex', {
                    initialValue: detailInfo?.sex,
                    rules: [{ required: true, message: '请选择性别' }],
                  })(
                    <Select placeholder="请选择" style={{ width: 350 }}>
                      <Option key={1}>男</Option>
                      <Option key={2}>女</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="&#12288;部门&#12288;&#12288;">
                  {getFieldDecorator('departmentName', {
                    initialValue: detailInfo?.departmentName,
                  })(<Input style={{ width: 350 }} />)}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="职务&#12288;&#12288;">
                  {getFieldDecorator('positionId', {
                    initialValue: detailInfo?.positionId,
                    rules: [{ required: true, message: '请选择职务' }],
                  })(
                    <Select placeholder="请选择" style={{ width: 350 }}>
                      {this.renderOptionsPosition()}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="&#12288;工号&#12288;&#12288;">
                  {getFieldDecorator('employeeNo', {
                    initialValue: detailInfo?.employeeNo,
                  })(<Input style={{ width: 350 }} />)}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="&#12288;邮箱&#12288;&#12288;">
                  {getFieldDecorator('email', {
                    initialValue: detailInfo?.email,
                  })(<Input style={{ width: 350 }} />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={12} sm={24}>
                <FormItem label="&#12288;出生年月">
                  {getFieldDecorator('birthday', {
                    initialValue: detailInfo?.birthday ? moment(detailInfo?.birthday) : '',
                  })(<DatePicker />)}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="手机号&#12288;">
                  {getFieldDecorator('mobile', {
                    initialValue: detailInfo?.mobile,
                    rules: [{ required: true, message: '请输入手机号' }],
                  })(<Input style={{ width: 350 }} />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={12} sm={24}>
                <FormItem label="&#12288;婚姻状况">
                  {getFieldDecorator('marriageStatus', {
                    initialValue: detailInfo?.marriageStatus,
                  })(
                    <Select placeholder="请选择" style={{ width: 350 }}>
                      <Option key={1}>未婚</Option>
                      <Option key={2}>已婚</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="密码&#12288;&#12288;">
                  {getFieldDecorator('password', {
                    initialValue: detailInfo?.password,
                    rules: [{ required: true, message: '请输入密码' }],
                  })(<Input placeholder="" style={{ width: 350 }} />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={12} sm={24}>
                <FormItem label="&#12288;卡号&#12288;&#12288;">
                  {getFieldDecorator('cardNo', {
                    initialValue: detailInfo?.cardNo,
                  })(<Input style={{ width: 350 }} />)}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="&#12288;证件号&#12288;">
                  {getFieldDecorator('identityNo', {
                    initialValue: detailInfo?.identityNo,
                  })(<Input style={{ width: 350 }} />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
          <Alert message="家属信息" type="info" style={{ marginBottom: 10, marginTop: 10 }} />
          <div>
            <Button type="primary" icon="plus" onClick={this.handleAdd}>
              新增
            </Button>
          </div>
          <SimpleTable
            selectedRows={false}
            loading={loading}
            data={{ list: familyList }}
            columns={columns}
            onChange=""
            rowKey="key"
          />
        </Card>
        <div style={{ textAlign: 'center' }}>
          <Button type="primary" style={{ marginRight: 20 }} onClick={this.handleSubmit}>
            提交
          </Button>
          <Button type="" onClick={this.handleCancel}>
            返回
          </Button>
        </div>
      </PageHeaderLayout>
    );
  }
}
